<template>
	<view class="container">
		<!-- 检索 -->
		<!-- <view class="search flex-row" :class="{input:this.query.keywords}"> -->
		<view class="search flex-row">
			<uni-icons class="icon" type="search" size="20" color="#777"></uni-icons>
			<input class="input" type="text" v-model="query.keywords" placeholder="请输入关键字" @input="listenInput" />
			<!-- <view class="btn flex-column" @tap="setHistory">检索</view> -->
			<view class="btn flex-column" @tap="searchList">检索</view>
		</view>
		<!-- 默认列表 -->
		<scroll-view class="body" v-show="!isShow" croll-y="true">
			<view class="card">
				<view class="title flex-row">
					<text class="text">历史搜索</text>
					<uni-icons type="trash" size="20" @tap="clearHistory"></uni-icons>
				</view>
				<view class="history flex-flow">
					<view v-for="(item,index) in history" @tap="clickKeywords(item.keyword)" :key="index"
						class="item flex-column text-ellipsis">{{item.keyword}}</view>
				</view>
			</view>
			<view class="card">
				<view class="title flex-row">
					<text class="text">热门文章</text>
				</view>
				<view class="list">
					<view v-for="(item,index) in hots" :key="index" @tap="addViews(item)"
						class="item flex-row text-ellipsis">
						<view class="name text-ellipsis">{{item.title}}</view>
						<view class="views">{{item.views}}</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 搜索之后显示的列表 -->
		<scroll-view class="body" scroll-y="true" v-show="isShow" :refresher-enabled="true"
			:refresher-triggered="triggered" @scrolltolower="getNextPage" @refresherrefresh="onRefresh"
			@refresherrestore="triggered='restore'">
			<card v-for="(item,index) in articleLists" :item="item" :key="index"></card>
			<uni-load-more v-show="articleLists.length" :status="loadStatus"></uni-load-more>
		</scroll-view>
	</view>
</template>

<script>
	const PAGE_SIZE = 4
	export default {
		data() {
			return {
				query: {
					page: 1,
					keywords: ''
				},
				hots: [],
				history: [],
				articleLists: [],
				isShow: false, //判断输入框是否为空
				loadStatus: 'more',
				isLoaded: false, //判断是否加载完成
				triggered: "restore" //下拉刷新复位
			}
		},
		onLoad() {
			//定义一个下拉刷新的变量		
			this._freshing = false;
			//1.获取热门文章列表
			this.getHostList();
			//2.设置搜索的缓存
			this.setHistory();
		},
		onShow() {
			//2.设置搜索的缓存
			this.setHistory();
			this.getHostList();
		},
		onHide() {
			//初始化
			this.articleLists = [];
			this.query.page = 1;
			this.query.keywords = '';
			this.isShow = false;


			//取出当前页面的关键词
			let history = uni.getStorageSync('history') || [];
			this.$request({
				url: "subject/history",
				method: "POST",
				data: {
					history: this.history
				},
				success: data => {
					console.log(data);
				}
			})
		},
		methods: {
			//绑定关键字
			listenInput(e) {
				this.articleLists = [];
				this.query.page = 1;

				e.detail.value ? this.isShow = true : this.isShow = false;
				//判断输入框是否为空 
				if (this.query.keywords = '') {
					//改变输入框的状态isShow
					this.isShow = false;
					uni.showToast({
						title: '关键字不能为空'
					});
					return;
				}
				// else{
				// 	this.isShow=true;
				// }
				this.query.keywords = e.detail.value

			},
			//1.获取热门文章列表
			getHostList() {
				this.$request({
					url: this.$api.getHotList,
					success: data => {

						this.hots = data
					}
				})
			},
			setHistory() {
				//0.从数据库请求对应的历史记录接口，请求之后，设置到当前的history缓存中 
				//1.先取缓存中是否有history，如果没有初始化数组
				let history = uni.getStorageSync('history') || [];
				//2.判断当前的关键字是否存在缓存中
				let current = history.some(item => item.keyword == this.query.keywords);
				//3.去重相同的关键字的缓存数据
				if (current) history = history.filter(item => item.keyword !== this.query.keywords);
				//4.缓存当前关键词
				if (this.query.keywords !== '') {
					history.unshift({
						keyword: this.query.keywords,
						time: new Date().getTime()
					})
				}

				//5.通过时间戳进行重新排序
				history.sort((a, b) => {
					return b.time - a.time;
				})
				//6.缓存的最大关键词做判断，不超过8个
				if (history.length > 8) history.pop()


				//7.设置关键词的缓存
				uni.setStorageSync('history', history)
				//8.赋值给当前的变量去渲染
				this.history = history
			},
			//检索文章列表
			searchList() {
				//初始化
				this.articleLists = [];
				this.query.page = 1;
				//在获取检索的文章列表
				this.getArticleList();
				//去除搜索框的空格  最后再设置缓存
				this.query.keywords.trim() && this.setHistory()
			},
			//获取文章列表
			getArticleList() {
				//设置loading
				this.loadStatus = 'loading'
				this.$request({
					url: this.$api.getSearchList,
					data: this.query,
					success: data => {
						//console.log(data);
						data = data.slice((this.query.page - 1) * PAGE_SIZE, PAGE_SIZE * this.query.page);

						//3.取消下拉刷新
						uni.stopPullDownRefresh()
						//判断数据会否加载完成
						this.isLoaded = data.length < PAGE_SIZE;
						//分页的公式：第一个值:页面减1,第二个值:页面的总条数*页面数 减1
						this.loadStatus = this.isLoaded ? 'noMore' : 'more';
						if (this.query.page > 1) {
							this.articleLists.push(...data)
						} else {
							this.articleLists = data;
						}
						// this.articleLists = data
						this.query.keywords ? this.isShow = true : this.isShow = false;

					},
					fail: err => {
						console.log(err)
					}
				})
			},
			//点击历史记录搜索
			clickKeywords(keywords = '') {
				this.articleLists = [];
				this.query.page = 1;
				this.query.keywords = keywords
				this.setHistory();
				this.getArticleList();
			},
			//清除所有的缓存--历史记录
			clearHistory() {
				uni.showModal({
					title: "删除",
					content: "是否确认删除历史搜索?",
					success: res => {
						if (res.cancel) return
						this.history = [];
						uni.removeStorageSync('history');

					}
				})
			},
			getNextPage() {
				if (this.isLoaded) return;
				this.query.page++;
				this.getArticleList();
			},
			//下拉刷新
			onRefresh() {
				//判断是否正在刷新
				if (this._freshing) return;
				this._freshing = true;
				//初始化
				this.query.page = 1;
				//再次请求当前页的列表
				this.getArticleList();
				//改变刷新的状态
				setTimeout(() => {
					this._freshing = false;
					this.triggered = false;
				}, 1000)

			},
			//热门文章点击阅读量添加一次
			addViews(item) {
				//点击增加一次
				item.views++;
				this.$request({
					url: this.$api.getHotList,
					method: "POST",
					data: {
						id: item.id,
						views: item.views
					}
				})
				//跳转对应的文章详情页
				this.$toPage('/pages/article/detall?id=' + item.id)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.search {
		height: 100rpx;
		padding: 10rpx 30rpx 0;
		position: relative;

		.icon {
			position: absolute;
			top: 36rpx;
			left: 60rpx;
		}

		.input {
			width: calc(100% - 140rpx);
			height: 72rpx;
			font-size: 28rpx;
			border-radius: 60rpx;
			background-color: #fff;
			padding: 0 30rpx 0 80rpx;
			box-sizing: border-box;
			transition: width 0.2s ease;
		}

		.btn {
			color: #FFF;
			width: 120rpx;
			height: 72rpx;
			border-radius: 40rpx;
			background-color: #FF6200;
			// opacity: 0;
			transition: all 0.2s ease;
		}

		// &.input {
		// 	.input {
		// 		width: calc(100% - 140rpx);
		// 	}

		// 	.btn {
		// 		opacity: 1;
		// 		width: 120rpx;
		// 	}
		// }
	}

	.body {
		background-color: #FFF;
		/* vh:可视化区域的高度  vw：可视化区域的宽度 */
		height: calc(100vh - 100rpx);
	}

	/* #ifdef H5 */
	/* 注释条件判断*/
	.container {
		height: calc(100vh - 44px - 50px - var(--status-bar-height));
		min-height: initial;
		/*initial 初始化 */
	}

	.body {
		height: calc(100vh - 100rpx - 44px - 50px - var(--status-bar-height));
	}

	/* #endif */
	.card {
		padding: 30rpx 30rpx 0;

		.title {
			margin-bottom: 30rpx;

			.text {
				font-size: 32rpx;
			}
		}

		/* 列表 */
		.list {
			.item {
				margin-bottom: 20rpx;

				&:nth-child(1) {

					.name,
					.views {
						color: red;
					}
				}

				&:nth-child(2) {

					.name,
					.views {
						color: orange;
					}

				}

				&:nth-child(3) {

					.name,
					.views {
						color: green;
					}

				}

				.name {
					width: calc(100% - 200rpx);
				}

				.views {
					color: #777;
				}
			}
		}

		/* 历史搜索 */
		.history {
			.item {
				color: #777;
				height: 60rpx;
				margin: 0 10rpx 30rpx;
				border-radius: 40rpx;
				background-color: #F5F5F5;
				width: calc(25% - 20rpx);
			}
		}
	}
</style>
